package com.yanqu.road.server.manger.activity.snowgarden;

import com.yanqu.road.entity.activity.ServerActivityMallDayBuyData;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MallDayBuyUserDayInfo {
    private int activityId;
    private long userId;
    //key: day
    private Map<Integer, MallDayBuyUserMallInfo> dayInfoMap = new ConcurrentHashMap<>();

    public MallDayBuyUserDayInfo(int activityId, long userId) {
        this.activityId = activityId;
        this.userId = userId;
    }

    public void addBuyData(ServerActivityMallDayBuyData buyData) {
        MallDayBuyUserMallInfo userDayMallInfo = dayInfoMap.get(buyData.getDay());
        if (userDayMallInfo == null) {
            userDayMallInfo = new MallDayBuyUserMallInfo(activityId, userId, buyData.getDay());
            dayInfoMap.put(buyData.getDay(), userDayMallInfo);
        }
        userDayMallInfo.addBuyData(buyData);
    }

    public MallDayBuyUserMallInfo getUserDayMallInfoNewIfNull(int day) {
        MallDayBuyUserMallInfo userDayMallInfo = dayInfoMap.get(day);
        if (userDayMallInfo == null) {
            synchronized (dayInfoMap){
                userDayMallInfo = dayInfoMap.get(day);
                if (userDayMallInfo == null) {
                    userDayMallInfo = new MallDayBuyUserMallInfo(activityId, userId, day);
                    dayInfoMap.put(day, userDayMallInfo);
                }
            }
        }
        return userDayMallInfo;
    }

    public void addMallBuy(int day, int mallId) {
        MallDayBuyUserMallInfo userDayMallInfo = getUserDayMallInfoNewIfNull(day);
        userDayMallInfo.addMallBuy(mallId);
    }

    public boolean isUserTodayBuyMall(int whichDay, int mallId) {
        MallDayBuyUserMallInfo userDayMallInfo = dayInfoMap.get(whichDay);
        if (userDayMallInfo == null) {
            return false;
        }
        return userDayMallInfo.isUserTodayBuyMall(mallId);
    }

    public void save() {
        List<MallDayBuyUserMallInfo> tempInfoList = new ArrayList<>();
        synchronized (dayInfoMap){
            tempInfoList.addAll(dayInfoMap.values());
        }

        for (MallDayBuyUserMallInfo userMallInfo : tempInfoList) {
            userMallInfo.save();
        }
    }

    public MallDayBuyUserMallInfo getDayInfo(int day) {
        return dayInfoMap.get(day);
    }
}
